package com.tanhua.dubbo.api;

import com.tanhua.dubbo.api.mongo.FriendApi;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;
import java.util.Map;

@DubboService
public class FriendApiImpl implements FriendApi {

    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     * 添加联系人
     *
     * @param userId
     * @param loginUserId
     */
    @Override
    public void addContacts(Long userId, Long loginUserId) {
        long timeMillis = System.currentTimeMillis();

        Query query = new Query(Criteria.where("userId").is(userId).and("friendId").is(loginUserId));
        if (!mongoTemplate.exists(query, Friend.class)) {
            Friend friend = new Friend();
            friend.setUserId(loginUserId);
            friend.setFriendId(userId);
            friend.setCreated(timeMillis);
            mongoTemplate.insert(friend);
        }
        query = new Query(Criteria.where("userId").is(loginUserId).and("friendId").is(userId));
        if (!mongoTemplate.exists(query, Friend.class)) {
            Friend friend = new Friend();
            friend.setUserId(userId);
            friend.setFriendId(loginUserId);
            friend.setCreated(timeMillis);
            mongoTemplate.insert(friend);
        }
    }

    /**
     * 获取好友列表
     *
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public List<Friend> getContacts(Long page, Long pagesize, Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        //判断数量是否超过10条
        long count = mongoTemplate.count(query, Comment.class);
        if (count > 10) {
            pagesize = 10L;
            query.skip((page - 1) * pagesize).limit(pagesize.intValue());
        }
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        return friendList;
    }


}
